<template>
  <div class="rental-project-application">
    <el-page-header @back="goBack" />
    <div class="application-container">
      <h1 class="application-title">
          {{ isEditMode ? '重新提交项目信息' : '独立选址项目申请' }}
      </h1>
      <el-divider />
      
      <el-form
        ref="formRef"
        :model="formData"
        label-width="150px"
        :rules="rules"
        label-position="left"
      >
        <!-- 基本信息 -->
        <h3 class="section-title">基本信息</h3>
        <el-divider />
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input 
                v-model="formData.projectName" 
                placeholder="请输入项目名称" 
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目编号" prop="projectCode">
              <el-input 
                v-model="formData.projectCode" 
                placeholder="请输入项目编号" 
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="投资方" prop="investor">
              <el-input 
                v-model="formData.investor" 
                placeholder="请输入投资方全称" 
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目产业类别" prop="industryCategory">
              <el-select
                v-model="formData.industryCategory"
                placeholder="请选择产业类别"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="item in industryOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 联系信息 -->
        <h3 class="section-title">联系信息</h3>
        <el-divider />
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactPerson">
              <el-input 
                v-model="formData.contactPerson" 
                placeholder="请输入联系人姓名" 
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input 
                v-model="formData.contactPhone" 
                placeholder="请输入联系电话" 
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="联系地址" prop="address">
          <el-input 
            v-model="formData.address" 
            placeholder="请输入详细联系地址" 
            clearable
          />
        </el-form-item>

        <!-- 项目信息 -->
        <h4 class="section-title">项目信息</h4>
        <el-divider />
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属园区" prop="parkName">
              <el-input 
                v-model="formData.parkName" 
                placeholder="请输入所属园区名称" 
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目周期(月)" prop="projectDuration">
              <el-input-number 
                v-model="formData.projectDuration" 
                :min="1" 
                :max="120"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col  :span="12">
               <el-form-item label="开始施工日期" prop="constructionStartDate">
          <el-date-picker
            v-model="formData.constructionStartDate"
            type="date"
            placeholder="选择开始施工日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
          </el-col>
          <el-col :span="12">
              <el-form-item label="计划总投资(万元)">
      <el-input-number 
        v-model="formData.totalInvestment" 
        :min="0"
        :precision="2"
        controls-position="right"
        style="width: 100%"
      />
    </el-form-item>
          </el-col>
        </el-row>
       
        

<el-row :gutter="20">
  <el-col :span="12">
     <el-form-item label="固定资产总投资(万元)">
      <el-input-number 
        v-model="formData.fixedAssetInvestment" 
        :min="0"
        :precision="2"
        controls-position="right"
        style="width: 100%"
      />
    </el-form-item>
  </el-col>
  <el-col :span="12">
      <el-form-item label="用地面积(亩)">
      <el-input-number 
        v-model="formData.landArea" 
        :min="0"
        :precision="2"
        controls-position="right"
        style="width: 100%"
      />
    </el-form-item>
  </el-col>
</el-row>

<el-row :gutter="20">
  <el-col :span="12">
    <el-form-item label="产值(万元/年)">
      <el-input-number 
        v-model="formData.annualOutputValue" 
        :min="0"
        :precision="2"
        controls-position="right"
        style="width: 100%"
      />
    </el-form-item>
  </el-col>
  <el-col :span="12">
     <el-form-item label="纳税额(万元/年)">
      <el-input-number 
        v-model="formData.annualTaxRevenue" 
        :min="0"
        :precision="2"
        controls-position="right"
        style="width: 100%"
      />
    </el-form-item>
  </el-col>
</el-row>

              <!-- 项目信息 -->
        <h5 class="section-title">选址信息</h5>
        <el-divider />
                
          <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="选址地址" prop="selectedaddress">
              <el-input 
                v-model="formData. selectedaddress" 
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

         <!-- 投资协议文件上传 -->
        <h6 class="section-title">附件上传</h6>
        <el-divider />


        <el-upload
          class="upload-area"
          action="#"
          multiple
          :limit="5"
          :file-list="contractFiles"
          :auto-upload="false"
          :on-change="handleFileChange"
          :on-remove="handleRemove"
          :on-exceed="handleExceed"
          drag
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            拖拽文件到此处或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持上传PDF、Word文档，单个文件不超过10MB
            </div>
          </template>
        </el-upload>
        

   




        <!-- 提交按钮 -->
        <el-form-item class="submit-btn">
          <el-button 
            type="primary" 
            size="large"
            @click="submitForm"
          >
            提交申请
          </el-button>
          <el-button 
            size="large"
            @click="resetForm"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const route = useRoute()

// 创建axios实例
const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 5000
})

const isEditMode = computed(() => route.query.editMode === 'true')
const editProjectId = computed(() => route.query.projectId || null)

const goBack = () => {
  router.go(-1)
}

// 表单数据
const formData = reactive({
  projectName: '',
  projectCode: '',
  investor: '',
  industryCategory: '',
  contactPerson: '',
  contactPhone: '',
  address: '',
  parkName: '',
  projectDuration: 12,
  constructionStartDate: '',
  totalInvestment: '',          // 计划总投资(万元)
  fixedAssetInvestment: '',     // 固定资产总投资(万元)
  landArea: '',                 // 用地面积(亩)
  annualOutputValue: '',        // 产值(万元/年)
  annualTaxRevenue: '',        // 纳税额(万元/年)
  selectedaddress: ''
})

// 产业类别选项
const industryOptions = ref([
  { value: '制造业', label: '制造业' },
  { value: '信息技术', label: '信息技术' },
  { value: '金融业', label: '金融业' },
  { value: '教育培训', label: '教育培训' },
  { value: '医疗健康', label: '医疗健康' },
  { value: '零售业', label: '零售业' },
  { value: '物流运输', label: '物流运输' },
  { value: '建筑工程', label: '建筑工程' },
  { value: '餐饮服务', label: '餐饮服务' },
  { value: '文化娱乐', label: '文化娱乐' },
  { value: '房地产', label: '房地产' },
  { value: '能源环保', label: '能源环保' },
  { value: '农业', label: '农业' },
  { value: '旅游酒店', label: '旅游酒店' },
  { value: '媒体广告', label: '媒体广告' },
  { value: '咨询服务', label: '咨询服务' },
  { value: '其他行业', label: '其他行业' }
])

// 表单验证规则
const rules = reactive({
  projectName: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  projectCode: [
    { required: true, message: '请输入项目编号', trigger: 'blur' }
  ],
  investor: [
    { required: true, message: '请输入投资方名称', trigger: 'blur' }
  ],
  industryCategory: [
    { required: true, message: '请选择产业类别', trigger: 'change' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入联系地址', trigger: 'blur' }
  ],
  parkName: [
    { required: true, message: '请输入所属园区', trigger: 'blur' }
  ],
  projectDuration: [
    { required: true, message: '请输入项目周期', trigger: 'blur' }
  ],
  constructionStartDate: [
    { required: true, message: '请选择开始施工日期', trigger: 'change' }
  ],
  selectedaddress: [
    { required: true, message: '请选择选址信息', trigger: 'blur' }
  ]
})

const formRef = ref(null)

// 加载项目数据（编辑模式）
const loadProjectData = async () => {
  if (isEditMode.value && editProjectId.value) {
    try {
      const response = await api.get(`/api/projects/${editProjectId.value}`)
      const project = response.data
      
      Object.assign(formData, {
        projectName: project.projectName,
        projectCode: project.projectCode,
        investor: project.investor,
        industryCategory: project.industryCategory,
        contactPerson: project.contactPerson,
        contactPhone: project.contactPhone,
        address: project.address,
        parkName: project.parkName,
        projectDuration: project.projectDuration,
        constructionStartDate: project.constructionStartDate,
        totalInvestment: project.totalInvestment,
        fixedAssetInvestment: project.fixedAssetInvestment,
        landArea: project.landArea,
        annualOutputValue: project.annualOutputValue,
        annualTaxRevenue: project.annualTaxRevenue,
        selectedaddress: project.selectedaddress
      })
    } catch (error) {
      console.error('加载项目数据失败:', error)
      ElMessage.error('加载项目数据失败')
    }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    // 验证表单
    const valid = await formRef.value.validate()
    if (!valid) {
      ElMessage.error('请检查表单填写是否正确')
      return
    }

    // 准备项目数据
    const projectData = {
      ...formData,
      type: 'independent',
      status: '审核中',
      state: 'inTalk',
      signDate: new Date().toISOString().split('T')[0]
    }

    if (isEditMode.value && editProjectId.value) {
      // 编辑模式 - 调用更新接口
      const response = await api.put(`/api/projects/${editProjectId.value}`, projectData)
      
      // 处理文件上传
      if (contractFiles.value.length > 0) {
        await uploadFiles(editProjectId.value)
      }
      
      ElMessage.success('项目更新成功')
    } else {
      // 新增模式 - 调用创建接口
      const response = await api.post(`/api/projects`, projectData)
      const newProject = response.data
      
      // 处理文件上传
      if (contractFiles.value.length > 0) {
        await uploadFiles(newProject.id)
      }
      
      ElMessage.success('项目创建成功')
    }
    
    // 跳转到项目列表页面
    router.push('/clientside')
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(`提交失败: ${error.response?.data?.message || error.message}`)
  }
}

// 上传文件的方法
const uploadFiles = async (projectId) => {
  const uploadPromises = contractFiles.value.map(async (file) => {
    const formData = new FormData()
    formData.append('file', file.raw)
    formData.append('projectId', projectId)
    formData.append('description', '项目申请文件')
    formData.append('category', 'application')
    formData.append('uploaderName', '当前用户')

    return await api.post(`/api/projects/${projectId}/files`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  })

  await Promise.all(uploadPromises)
  ElMessage.success(`成功上传 ${contractFiles.value.length} 个文件`)
}

// 重置表单
const resetForm = () => {
  formRef.value.resetFields()
  contractFiles.value = []
}

// 上传相关状态
const contractFiles = ref([])

// 文件上传处理
const handleFileChange = (file, fileList) => {
  // 检查文件大小
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB')
    return false
  }
  
  // 检查文件名是否重复
  const isDuplicate = fileList.some(f => 
    f.name === file.name && 
    f.uid !== file.uid
  )
  
  if (isDuplicate) {
    ElMessage.error(`文件 "${file.name}" 已存在`)
    return false
  }
  
  // 更新文件列表
  contractFiles.value = fileList.map(file => ({
    name: file.name,
    size: file.size,
    type: file.name.split('.').pop() || 'file',
    raw: file.raw
  }))
  return true
}

// 移除文件
const handleRemove = (file, fileList) => {
  contractFiles.value = fileList.map(file => ({
    name: file.name,
    size: file.size,
    type: file.name.split('.').pop() || 'file',
    raw: file.raw
  }))
}

// 超出限制
const handleExceed = () => {
  ElMessage.warning('最多只能上传5个文件')
}

onMounted(() => {
  loadProjectData()
})
</script>

<style scoped>
.rental-project-application {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.application-container {
  background-color: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.application-title {
  font-size: 24px;
  color: #333;
  margin: 0 0 10px 0;
  text-align: left;
}

.section-title {
  font-size: 18px;
  color: #409EFF;
  margin: 30px 0 15px 0;
  text-align: left;
}

.el-divider {
  margin: 15px 0;
}

.submit-btn {
  margin-top: 50px;
  text-align:right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .application-container {
    padding: 20px;
  }
  
  .application-title {
    font-size: 20px;
  }
  
  .section-title {
    font-size: 16px;
  }
  
  :deep(.el-form-item__label) {
    width: 100% !important;
    text-align: left;
  }
  
  :deep(.el-form-item__content) {
    margin-left: 0 !important;
  }

  
}

/* 上传区域样式 */

.upload-area {
  width: 300px;
  height: 300px;
  margin-bottom: 20px;

}

:deep(.el-upload-dragger) {
  padding: 40px;
  border-radius: 8px;
}

:deep(.el-icon--upload) {
  font-size: 67px;
  color: #c0c4cc;
  margin: 40px 0 16px;
  line-height: 50px;
}

:deep(.el-upload__text) {
  color: #606266;
  font-size: 14px;
  text-align: center;
}

:deep(.el-upload__text em) {
  color: #409eff;
  font-style: normal;
}

:deep(.el-upload__tip) {
  margin-top: 15px;
  color: #606266;
  font-size: 14px;
  text-align: center;
}

.uploaded-files-list {
  margin-top: 20px;
}


</style>


